package dry.example.gui;

import javax.swing.*;

public class GroupLayoutDemo {
    public static void main(String[] args) {
        // 创建主窗口
        JFrame frame = new JFrame("GroupLayout 示例");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 200);

        // 创建面板
        JPanel panel = new JPanel();

        // 设置 GroupLayout 布局
        GroupLayout layout = new GroupLayout(panel);
        panel.setLayout(layout);

        // 自动添加间隙（true 表示启用自动间隙）
        layout.setAutoCreateGaps(true);
        layout.setAutoCreateContainerGaps(true);

        // 创建组件
        JLabel userLabel = new JLabel("用户名:");
        JTextField userField = new JTextField(15); // 宽度为15字符

        JLabel passLabel = new JLabel("密码:");
        JPasswordField passField = new JPasswordField(15);

        JButton loginButton = new JButton("登录");
        JButton cancelButton = new JButton("取消");

        // 设置水平组
        layout.setHorizontalGroup(
                layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
                                .addComponent(userLabel)
                                .addComponent(passLabel))
                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                                .addComponent(userField)
                                .addComponent(passField)
                                .addGroup(layout.createSequentialGroup()
                                        .addComponent(loginButton)
                                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(cancelButton)))
        );

        // 设置垂直组
        layout.setVerticalGroup(
                layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                .addComponent(userLabel)
                                .addComponent(userField))
                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                .addComponent(passLabel)
                                .addComponent(passField))
                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                .addComponent(loginButton)
                                .addComponent(cancelButton))
        );

        // 将面板加入窗口
        frame.add(panel);
        frame.setVisible(true);
    }
}
